package com.xiyou.luckdraw.web.controller;

import com.xiyou.luckdraw.api.dal.entitys.AnswerBank;
import com.xiyou.luckdraw.api.dal.mapper.luckdraw.AnswerBank1Mapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: TestApiCpntroller
 * @Description:
 * @author: limingxing
 * @Date: 2019-10-07 19:39
 */
@RestController
@RequestMapping("/api")
@Api(value = "TestApiCpntroller", tags = "测试Api接口")
public class TestApiCpntroller {

    @ApiOperation(value = "创建图书", notes = "创建图书")
    @PostMapping("/test")
    public String test() {
        return "ok";
    }


    @Autowired
    AnswerBank1Mapper answerBank1Mapper;


   /* @RequestMapping("/uploadFile")
    public Map<String, Object> bathAddData(@RequestParam("file") MultipartFile file) {
        InputStream is = null;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            is = file.getInputStream();
            List<Object> entityList = ExcelUtils.importDataFromExcel(new AnswerBank(), is, file.getOriginalFilename());
            System.out.println(entityList.size() + "---------");
            if (entityList.size() == 0) {
                map.put("status", "0");
                map.put("msg", "导入数据不能为空");
            } else if (entityList.size() > 10) {
                map.put("status", "1");
                map.put("msg", "数据条数不准大于10条");
            } else {
                Map<String, Object> Resmap = queryTestService.batchAddData(entityList);
                // System.out.println(Resmap.get("success")+"---"+Resmap.get("data"));
                int totalNum = entityList.size();
                int failed = totalNum - Integer.parseInt(Resmap.get("success").toString());
                map.put("status", "2");
                map.put("msg", "导入成功");
                map.put("success", Resmap.get("success"));
                map.put("totalNum", totalNum);
                map.put("failed", failed);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            is = null;
        }
        System.out.println(map.get("msg") + "--" + map.get("status"));
        return map;
    }*/


    @ApiOperation(value = "upload", notes = "upload")
    @PostMapping("/upload")
    public Object upload(@RequestParam(value = "file") MultipartFile file) {
        List<AnswerBank> list = this.getExcelInfo(file);
        //拿到读取数据，做数据批量处理，具体根据具体需求，进行判断
        return "";
    }

    public List<AnswerBank> getExcelInfo(MultipartFile mFile) {
        String fileName = mFile.getOriginalFilename();// 获取文件名
        List<AnswerBank> list = new ArrayList<>();
        try {
            if (!validateExcel(fileName)) {// 验证文件名是否合格
                return null;
            }
            boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
            if (isExcel2007(fileName)) {
                isExcel2003 = false;
            }
            list = createExcel(mFile.getInputStream(), isExcel2003, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public List<AnswerBank> createExcel(InputStream is, boolean isExcel2003, List<String> error) {
        List<AnswerBank> list = new ArrayList<>();
        try {
            Workbook wb = null;
            if (isExcel2003) {// 当excel是2003时,创建excel2003
                wb = new HSSFWorkbook(is);
            } else {// 当excel是2007时,创建excel2007
                wb = new XSSFWorkbook(is);
            }
            list = readExcelValue(wb, error);// 读取Excel里面客户的信息
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public boolean validateExcel(String filePath) {
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
            String errorMsg = "文件名不是excel格式";
            return false;
        }
        return true;
    }
    // 是否是2003的excel，返回true是2003
    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    // 是否是2007的excel，返回true是2007
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }
    /**
     *
     * @Title: readExcelValue
     * @Description: 读取Excel信息
     * @return List<T>
     * @author fun
     * @date 2018年9月5日
     */
    public List<AnswerBank> readExcelValue(Workbook wb, List<String> error) {
  //      ReadExcel readExcel = new ReadExcel();
        int totalRows = 10;
        int totalCells =20;
        // 得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        // 得到Excel的行数
        totalRows = sheet.getPhysicalNumberOfRows();
        // 得到Excel的列数(前提是有行数)
        if (totalRows > 1 && sheet.getRow(0) != null) {
            totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }

        System.out.println("aaaaaaa"+ sheet.getRow(0).getPhysicalNumberOfCells());
        // 循环Excel行数
        List<AnswerBank> list = new ArrayList<>();
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            AnswerBank model = new AnswerBank();
            // 循环Excel的列
            for (int c = 0; c < totalCells; c++) {
                model.setStatus(new Long(1));//默认为启用状态

                Cell answerTitle = row.getCell(0);//题目
                if (answerTitle != null) {
                    answerTitle.setCellType(Cell.CELL_TYPE_STRING);
                    model.setAnswerTitle((answerTitle.getStringCellValue()));
                }
                Cell A = row.getCell(1);//选项A
                if (A != null) {
                    A.setCellType(Cell.CELL_TYPE_STRING);
                    model.setA((A.getStringCellValue()));
                }

                Cell B = row.getCell(2);//选项B
                if (B != null) {
                    B.setCellType(Cell.CELL_TYPE_STRING);
                    model.setB((B.getStringCellValue()));
                }

                Cell C = row.getCell(3);//选项C
                if (C != null) {
                    C.setCellType(Cell.CELL_TYPE_STRING);
                    model.setC((C.getStringCellValue()));
                }
                Cell D = row.getCell(4);//选项D
                if (D != null) {
                    D.setCellType(Cell.CELL_TYPE_STRING);
                    model.setD((D.getStringCellValue()));
                }
                Cell correctAnswer = row.getCell(5);//正确答案(当前只支持单选)
                if (correctAnswer != null) {
                    correctAnswer.setCellType(Cell.CELL_TYPE_STRING);
                    model.setCorrectAnswer(new Long(correctAnswer.getStringCellValue()));
                }
                Cell level = row.getCell(6);//
                if (level != null) {
                    level.setCellType(Cell.CELL_TYPE_STRING);
                    model.setLevel(new Long(level.getStringCellValue()));
                }

                /*if (null != cell) {
                    if (c == 0) {
                        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                            model.setAnswerTitle(cell.getStringCellValue());
                        }
                    } else if (c == 1) {
                        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                            model.setA(cell.getStringCellValue());
                        }
                    } else if (c == 2) {
                        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                            model.setB(cell.getStringCellValue());
                        }
                    }else if (c == 3) {
                        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                            model.setC(cell.getStringCellValue());
                        }
                    }else if (c == 4) {
                        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                            model.setD(cell.getStringCellValue());
                        }
                    }else if (c == 5) {
                        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                            model.setCorrectAnswer(new Long(cell.getStringCellValue()));
                        }
                    }else if (c == 6) {
                        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                            model.setLevel(new Long(cell.getStringCellValue()));
                        }
                    }
                }*/
                list.add(model);
                model.setCreateTime(new Date());
                model.setModifyTime(new Date());
                int result = answerBank1Mapper.insert(model);
                System.out.println("******************************"+ result);
            }

        }
        return list;
    }
}
